import numpy as np
import pygetwindow as gw
import pyautogui
from PIL import Image
import keyboard

screenLocation = []


def capture_window(window_title, save_path='/images/screenshot.png'):
    # 获取所有窗口
    all_windows = gw.getAllTitles()

    # 查找包含指定关键词的窗口标题
    matching_windows = [
        title for title in all_windows if window_title in title]

    if not matching_windows:
        raise ValueError(
            f"No window found with title containing: {window_title}")

    # 获取选定窗口对象
    window = gw.getWindowsWithTitle(matching_windows[0])[0]

    # 将窗口置顶（可选，如果窗口未被遮挡则不需要）
    try:
        window.activate()
    except:
        print("Failed to activate the window. Ensure it's not minimized.")

    # 获取窗口在屏幕上的位置和大小
    x, y, width, height = window.left, window.top, window.width, window.height
    screenLocation.append([x, y])
    # 使用 pyautogui 截图
    screenshot = pyautogui.screenshot(
        region=(x+9, y+44, width-8-9, height-44-8))

    # 保存截图
    screenshot.save(save_path)
    print(f"Screenshot saved as {save_path}")


# 调用函数并传入你想要截取的窗口名称
capture_window(
    "钢琴块2", "C:/Users/user/Desktop/myTest/python-test/images/captured_window.png")

# 打开图像并转换为灰度图
image = Image.open(
    'C:/Users/user/Desktop/myTest/python-test/images/captured_window.png').convert('L')

# 定义一个简单的二值化函数


def binarize(image, threshold=127):
    return image.point(lambda p: 255 if p > threshold else 0)


# 应用二值化
binary_image = binarize(image)

# 或者保存结果
binary_image.save(
    'C:/Users/user/Desktop/myTest/python-test/images/binary_image.jpg')

# 将二值化图像转换为 numpy 数组
binary_array = np.array(binary_image)

# 指定要检测的四个坐标点 (x1, y), (x2, y), (x3, y), (x4, y)
# 这里以 (100, 100), (150, 100), (200, 100), (250, 100) 为例
x_coords = [40, 40+80, 40+80*2, 40+80*3]
y = 360+44  # 假设 y 坐标相同


def check_and_click_black_pixels(binary_array, x_coords, y, screenLocation):
    base_x, base_y = screenLocation[0]
    for x in x_coords:
        if binary_array[y, x] == 0:
            # 计算实际屏幕坐标
            screen_x = base_x + x + 9
            screen_y = base_y + y + 44
            # 鼠标点击
            pyautogui.click(screen_x, screen_y)
            print(f"点击坐标 ({screen_x}, {screen_y})")


# 循环执行，直到用户按下向下箭头键
while not keyboard.is_pressed('down'):
    # 重新捕获窗口并更新二值化图像
    capture_window(
        "钢琴块2", "C:/Users/user/Desktop/myTest/python-test/images/captured_window.png")

    # 打开图像并转换为灰度图
    image = Image.open(
        'C:/Users/user/Desktop/myTest/python-test/images/captured_window.png').convert('L')

    # 应用二值化
    binary_image = binarize(image)

    # 将二值化图像转换为 numpy 数组
    binary_array = np.array(binary_image)

    # 检查并点击黑色像素
    check_and_click_black_pixels(binary_array, x_coords, y, screenLocation)
